<template>
  <div :id="echartId" :style="chartStyle" />
</template>

<script setup>
import * as echarts from "echarts";
import { ref, onBeforeUnmount, onMounted,  } from "vue";

const props = defineProps({
  chartStyle: {
    type: Object,
    default: () => ({
      width: "100%",
      height: "100%",
    }),
  },
  chartOption: {
    type: Object,
    default: () => ({}),
    required: true,
  },
});

const echartId = ref(`echarts-id-${parseInt(Math.random() * 1000000)}`);

const drawChart = () => {
  const echart = echarts.init(document.getElementById(echartId.value));
  echart.setOption(props.chartOption, { notMerge: true });
  // 监听窗口大小变化，重新渲染图表
  window.addEventListener("resize", () => {
    echart.resize();
  });
};

// 在组件挂载后初始化ECharts图表
onMounted(() => {
  drawChart();
});

// 在组件销毁前清理ECharts实例和移除事件监听
onBeforeUnmount(() => {
  const echart = echarts.getInstanceByDom(
    document.getElementById(echartId.value)
  );
  if (echart) {
    echart.dispose();
  }
  window.removeEventListener("resize", () => {
    const echart = echarts.getInstanceByDom(
      document.getElementById(echartId.value)
    );
    if (echart) {
      echart.resize();
    }
  });
});
</script>
